const { EventEmitter } = require('events');

class ProgressIndicator extends EventEmitter {
  constructor(parent = null, scale = 1) {
    super();
    this.progress = 0;

    this.parent = parent;
    this.scale = scale;

    this.splitCursor = 0;
  }

  _advance(span) {
    if (this.progress >= 1) {
      return;
    }
    this.progress += span;
    // if (this.progress > 1) {
    //   this.progress = 1;
    // }
    this.emit('progress', this.progress);
    if (this.parent) {
      this.parent._advance(span * this.scale);
    }
  }

  /**
   * @param {Number} span 跨度
   * @param {Number} total 分母
   * @return {ProgressIndicator[]}
   */
  advance(span, total = 1) {
    if (this.splitCursor > 0) {
      throw new Error('already splited');
    }
    return this._advance(span / total);
  }

  finish() {
    this._advance(1 - this.progress);
  }

  /**
   * @param {Number[]} spans 分割比例
   * @param {Number} total 分母
   * @return {ProgressIndicator[]}
   */
  split(spans, total = 1) {
    if (this.splitCursor > 0) {
      throw new Error('already splited');
    }
    const sum = spans.reduce((sum, i) => sum + i, 0);
    if (sum !== total) {
      throw new Error(`sum expected to be ${total}, but be ${sum}`);
    }
    this.splitCursor = 1;
    return spans.map((span) => new ProgressIndicator(this, span / total));
  }
}

module.exports = ProgressIndicator;
